/* eslint-disable @iceworks/best-practices/recommend-polyfill */
import DrawerFooter from '@/components/DrawerFooter';
import { useStore } from '@/hooks';
import { Button, Dialog, Form, Table, Divider, Notification } from '@alifd/next';
import { t } from '@lingui/macro';
import { observable } from 'mobx';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';
import { FieldsGrid, TitleGrid } from '../stores/definitions_set';
import ChargeForm from './ChargeForm';

const FromItem = Form.Item;
const ShareShiftSet = (props) => {
  const {
    routePriceId,
    modal,
    onSubmit,
    onCancel,
    line,
  } = props;
  // eslint-disable-next-line no-unused-vars
  const { scSelfStore: store } = useStore();
  const isViewMode = modal[0] === 'view';
  const formProps = isViewMode ? { field: false } : {};
  const [share] = useState(() => observable({}));
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [fixedShifts, setFixedShifts] = useState([]);
  const [idx, setIdx] = useState(-1);
  const [curCharge, setCurCharge] = useState();
  const [isCreate, setIsCreate] = useState(true);
  const [filedValues] = useState(() => ({
    1: ['firstTime', 'lastTime', 'interval'].map((p) => `flowShifts.${p}`),
    2: ['scheduleItems[0].date'].map((p) => `fixedShifts.${p}`),
    3: ['scheduleItems[0].date'].map((p) => `fixedShifts.${p}`),
    undefined: [],
  }));
  const [shiftTimes, setShiftTimes] = useState([]);

  useEffect(() => {
    (async () => {
      const {
        isCreate: curIsCreate,
        shiftInfo,
      } = await store.isCreateRsShift(routePriceId);
      const { startMainArea, startMinorAreas, endMainArea, endMinorAreas } = toJS(line);
      const relevancy = await store.getShiftsRoute({
        onCityId: startMainArea,
        endCityId: endMainArea,
        onStationId: startMinorAreas[0],
        offStationId: endMinorAreas[0],
        enable: true,
      });
      const result = Array.from(
        new Set(
          relevancy.flatMap((item) =>
            item.relateRoutes.flatMap((p) => p.schedule)
          )
        )
      );
      setShiftTimes(result);
      const { scheduleItems } = shiftInfo?.fixedShifts || {};
      if (!curIsCreate) {
        const parseScheduleItems = scheduleItems?.map((item) => ({
          ...item,
          carpoolUnitPrice: item.carpoolUnitPrice?.RMB,
        })) || [];
        _.assign(share, { SHIFT_INFO: shiftInfo, ...shiftInfo });
        setFixedShifts(parseScheduleItems);
      }
      setIsCreate(curIsCreate);
    })();
  }, [routePriceId]);

  // 重载definitions中的定义，处理一些根据上下文的动态定义
  const overrideModel = {
    startNames: {
      label: t`开始站点`,
      ui: {
        renderer: (_) => <span style={{ fontWeight: 500 }}>{line?.beginAreaName}</span>,
      },
    },
    endNames: {
      label: t`结束站点`,
      ui: {
        renderer: (_) => <span style={{ fontWeight: 500 }}>{line?.endAreaName}</span>,
      },
    },
    fixedShifts: {
      scheduleItems: [{
        date: {
          ui: {
            renderer: () => (
              <>
                <Button type="primary" style={{ marginBottom: 10 }} onClick={() => handleAddState('sc')}>{t`添加班次`}</Button>
                {shiftTimes.length > 0 && <div><span style={{ color: 'red', fontWeight: 500 }}>{t`注：当前线路已关联班次时间 (${shiftTimes.join('、')})`}</span></div>}
                <Table
                  hasBorder={false}
                  dataSource={fixedShifts}
                  columns={columns}
                  onRowClick={(_, index) => setIdx(index)}
                />
              </>
            ),
            span: 3,
          },
        },
      }],
    },
  };

  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    (async () => {
      editCtx.origin = _.cloneDeep({});
      _.assign(share, {});
      // 添加操作,设置默认值
      _.set(share, 'shiftType', 2);
      _.set(share, 'state', true);
      _.set(share, 'day', 3);
      _.set(share, 'routePriceId', routePriceId);
    })();
  }, []);

  const columns = [
    {
      title: t`序号`,
      dataIndex: 'id',
      align: 'center',
      cell: (v, i) => <span>{i + 1}</span>,
    },
    {
      title: t`班次时间`,
      dataIndex: 'date',
      width: 200,
      align: 'center',
    },
    {
      title: t`下单截止时间(无空位时/单位分)`,
      dataIndex: 'payEndTime',
      width: 200,
      align: 'center',
    },
    {
      title: t`下单截止时间(有空位时/单位分)`,
      dataIndex: 'notGroupPayEndTime',
      width: 200,
      align: 'center',
    },
    {
      title: t`操作`,
      dataIndex: 'name',
      align: 'center',
      width: 300,
      cell: (v, i, r) => (
        <>
          <Button type="primary" text onClick={() => handleCurCharge(r, 'sc')}>{t`编辑`}</Button>
          <Divider direction="ver" />
          <Button type="primary" text style={{ color: 'red' }} onClick={() => handleDeleteState(i, 'sc')}>{t`删除`}</Button>
        </>
      ),
    },
  ];

  if (!share) return <></>;

  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(share, name, value);
    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const handleAddState = () => {
    const data = {
      id: new Date().getTime(),
      date: '08:00',
      payEndTime: 5,
      notGroupPayEndTime: 0,
    };
    setFixedShifts((pre) => {
      const cloneData = [...pre];
      cloneData.push(data);
      return cloneData;
    });
  };

  const handleDeleteState = (i) => {
    setFixedShifts((pre) => {
      const arr = [...pre];
      arr.splice(i, 1);
      return arr;
    });
  };

  const handleCurCharge = (values) => {
    setCurCharge({
      values,
    });
  };


  const chargeOnSubmit = (values, errors) => {
    if (errors) {
      return;
    }
    const { date, payEndTime, notGroupPayEndTime } = values;
    const newInx = idx;
    setFixedShifts((pre) => {
      const newCharge = [...pre];
      newCharge[newInx].date = date;
      newCharge[newInx].payEndTime = payEndTime;
      newCharge[newInx].notGroupPayEndTime = notGroupPayEndTime;
      return newCharge;
    });
    setCurCharge(false);
  };


  const handleCancel = () => {
    // eslint-disable-next-line no-param-reassign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => { v !== undefined && (r[k] = v); }))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  const handleSubmit = (_value, errors, _field) => {
    if (!_.isEmpty(errors)) {
      return;
    }
    const cloneShifts = fixedShifts;
    const currentNext = verifyShifts(cloneShifts);
    if (!currentNext) return;
    if (Number(share.shiftType) === 2 && cloneShifts.length <= 0) {
      return Notification.open({
        title: '警告⚠️',
        content: t`固定班次不可为空!`,
        type: 'warning',
      });
    }
    _.set(share, 'list', fixedShifts);
    onSubmit?.(share, isCreate);
  };

  function verifyShifts(shifts) {
    // 检查 value 属性是否是唯一的
    const isUnique = shifts.every((item, index, array) =>
      array.findIndex((obj) => obj.date === item.date) === index);
    if (!isUnique) {
      Notification.open({
        title: '警告⚠️',
        content: t`班次时间不能相同!`,
        type: 'warning',
      });
    }
    return isUnique;
  }

  return (
    <>
      <Form
        isPreview={isViewMode}
        {...formProps}
        value={share}
        inline
        onChange={handleChange}
        useLabelForErrorMessage
      >
        <TitleGrid title={t`站点信息`} />
        <FieldsGrid
          formData={share}
          overrideModel={overrideModel}
          mode={'view'}
          columns={2}
          fields={['startNames', 'endNames']}
        />
        <TitleGrid title={t`班次信息`} />
        <FieldsGrid
          formData={share}
          overrideModel={overrideModel}
          mode={modal[0]}
          columns={3}
          fields={['shiftType', 'day', 'state', 'ignoreDays'].concat(filedValues[share.shiftType])}
        />
        <TitleGrid title={t`其他`} />
        <FieldsGrid
          formData={share}
          overrideModel={overrideModel}
          mode={modal[0]}
          fields={['description'].map((p) => (share.shiftType === '1' ? `flowShifts.${p}` : `fixedShifts.${p}`))}
        />
        <DrawerFooter>
          <FromItem>
            {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
            <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
          </FromItem>
        </DrawerFooter>
      </Form>
      <Dialog
        visible={!!curCharge}
        onCancel={() => setCurCharge(false)}
        onClose={() => setCurCharge(false)}
        title={t`编辑班次【 ${idx + 1} 】`}
        style={{ width: '30%' }}
        footer={null}
      >
        <ChargeForm
          data={curCharge}
          onSubmit={(r, errors) => chargeOnSubmit(r, errors)}
          onCancel={() => setCurCharge(false)}
        />
      </Dialog>
    </>
  );
};

export default observer(ShareShiftSet);
